import { defineStore } from 'pinia';
import {
  doLogin as userLogin,
  logout as userLogout,
  getUserInfo,
  LoginData,
} from '@/api/user';
import service from '@/utils/request';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    role: '',
    admin: false,
    avatar: '',
    createBy: '',
    createTime: '',
    delFlag: '',
    email: '',
    loginDate: '',
    loginIp: '',
    nickName: '',
    params: {},
    phonenumber: '',
    postIds: '',
    remark: '',
    roleId: '',
    roleIds: '',
    roles: [],
    salt: '',
    searchValue: '',
    sex: '',
    status: '',
    updateBy: '',
    updateTime: '',
    userId: 0,
    userName: '',
    userType: '',
    dept: {
      deptName: '',
    },
    permissions: [],
    // role: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
    deptName(state: UserState): string | undefined {
      return state?.dept?.deptName;
    },
  },

  actions: {
    // switchRoles() {
    //   return new Promise((resolve) => {
    //     this.role = this.role === 'user' ? 'admin' : 'user';
    //     resolve(this.role);
    //   });
    // },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const res = await getUserInfo();
      this.setInfo({
        ...res,
        ...res.user,
      });
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.token);
        service.setToken(res.token);
        return res;
      } catch (err) {
        clearToken();
        throw err;
      }
    },

    // Logout
    async logout() {
      await userLogout();

      this.resetInfo();
      clearToken();
      removeRouteListener();
    },
  },
});

export default useUserStore;
